package ru.tulupov.toyfactory.pattern.impl;

import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;

import ru.tulupov.toyfactory.model.Playable;
import ru.tulupov.toyfactory.model.StatisticManager;
import ru.tulupov.toyfactory.model.ThreadManager;
import ru.tulupov.toyfactory.model.ToyBrokenException;
import ru.tulupov.toyfactory.pattern.Consumer;
import ru.tulupov.toyfactory.pattern.Storage;

public class PlayableConsumer extends Consumer<Playable> implements Observer {
	private static final Logger LOGGER = Logger
			.getLogger(PlayableConsumer.class);
	private HashMap<Playable, Integer> map;

	public PlayableConsumer(Storage<Playable> storage) {
		super(storage);
		map = new HashMap<Playable, Integer>();
		ThreadManager.getInstance().addObserver(this);
	}

	private void updateStatistics(Playable element) {
		Integer count = map.get(element);
		if (count == null) {
			map.put(element, 1);
		} else {
			map.put(element, count + 1);
		}
	}

	@Override
	protected void onReceive(Playable element) {
		try {
			element.play();

			updateStatistics(element);
		} catch (ToyBrokenException e) {
			LOGGER.error(String.format("A toy [%s] was broken.", element));
		}
	}

	@Override
	public void interrupt() {

		ThreadManager.getInstance().interruptAll(this);
		super.interrupt();
	}

	@Override
	public void update(Observable observable, Object obj) {

		interrupt();
	}

	@Override
	protected void onStop() {
		StatisticManager.getInstance().update(map);

	}
}
